package edu.netjava.ServerChar;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: set up a server socket to wait the client to connect
 * @author tan
 * @version 1.0.0
 */

public class ServerChar {

	/**
	 * define the specified port
	 */
	int port;

	/**
	 * constructor to initial the port
	 * 
	 * @param port:the
	 *            port to bind
	 */
	public ServerChar(int port) {
		this.port = port;
	}

	/**
	 * set up the server to listen client
	 */
	public void setUpServer() {

		try {
			ServerSocket ss = new ServerSocket(port);
			System.out.println("Server is waiting at " + port + "...");

			
			String clientWrite = "";
			while (true) {

				Socket client = ss.accept();
				clientWrite = "Welcome client from " +client.getRemoteSocketAddress()+"\r\n";
				
				
				
				InputStream is = client.getInputStream();
				OutputStream os = client.getOutputStream();
				DataInputStream dis = new DataInputStream(is);
				
				os.write(clientWrite.getBytes());
				clientWrite = "Say Something...\r\n";
				os.write(clientWrite.getBytes());
				
				while(!clientWrite.equalsIgnoreCase("bye")){
					clientWrite =  dis.readLine();
					
					
					String clientSay = "\nComing from "
							+ client.getRemoteSocketAddress() + " Clinet Say : \r\n";
					clientSay += clientWrite+"\n\r\n"+"Continue...\n\r";
					
					os.write(clientSay.getBytes());
					
					os.flush();
				}
				
				
				
				client.close();
				
				
				

			}

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	
	
	
	public static void main(String arg[]){
		ServerChar sc = new ServerChar(9999);
		sc.setUpServer();
	}

}
